import checkList from './check.js'
import useAiStore from '../../../store/ai';
const store = useAiStore();
// import { postLog } from '../serve'
import  dsbridge  from "./dsbridge.js";
const { postLog } = require("../serve/index.js");

import request from "./request/request.js"
import { isH5 } from './Eplatform.js';
// #ifndef H5
// 创建音频组件
const innerAudioContext = uni.createInnerAudioContext();
innerAudioContext.autoplay = false;
innerAudioContext.src = '';

let plugin = requirePlugin("QCloudAIVoice")
// 一句话识别、语音合成
plugin.setQCloudSecret(1358329933, 'AKIDHQNDtOiqlT0NXT0RiowwlcKrEQQQFsJZ', '84pOKAp9VltY5SgnlYCfz85tX1KUSIyT', false);
// #endif
//设置腾讯云账号信息，其中appid是数字，secret是字符串，
const app = getApp();
// let ident = '42118199902106320' //假身份证
// let data = ident.toUpperCase() //转换成大写
// console.log(IdentityCodeValid.validateIdent.IdentityCodeValid(data)) //得到 false

// let realData = '420102199003078776' //真身份证
// let data1 = realData.toUpperCase()
// console.log(IdentityCodeValid.validateIdent.IdentityCodeValid(data1)) //得到true
let timeOutWorkTypes = ''
// #ifdef H5
timeOutWorkTypes = ['none']
// #endif
// #ifndef H5
timeOutWorkTypes = ['2g', '3g', 'none', 'unknown']
// #endif

let tapBarList = ['/pages/index/index']

export const navBack = () => {
	// const dsbridge = require("./dsbridge");
	let routes = getCurrentPages()

	let backHome = routes[routes.length - 1].options.scene || routes[routes.length - 1].options.share ? 1 : routes[routes.length - 1].options.backHome
	// 非H5程序。所有的分享。或者复制链接打开的页面，返回全部跳转首页
	if ((backHome && isH5) || ((backHome || (routes.length == 1)) && !isH5)) {
        uni.navigateTo({
          url: '/ai/pages/index'
        })
	} else {
		//	#ifdef H5
		if (routes.length <= 1) {
			dsbridge.navigateBack()
		} else {
			uni.navigateBack({
				delta: 1
			});
		}
		//	#endif
		//	#ifndef H5
		uni.navigateBack({
			delta: 1
		});
		//	#endif
	}
}
/**
 * 跳转到指定页面url
 * 支持tabBar页面
 * @param {string}  url   页面路径
 * @param {object}  query 页面参数
 * @param {string}  modo  跳转类型(默认navigateTo)
 */
export const navTo = async (url, query = {}, mode = 'navigateTo') => {
	if (!url || url.length == 0) {
		return false
	}
	let workType = await new Promise((resolved, rejected) => {
		uni.getNetworkType({
			success(res) {
				const networkType = res.networkType
				resolved(networkType);
			},
			fail() {
				// 失败的时候让其跳转
				resolved('wifi');
			}
		})
	})

	if (timeOutWorkTypes.includes(workType)) {
		//   缺省页面
		uni.navigateTo({
			url: `/packageA/pages/outTime/index`
		})
		return
	}
	// tabBar页面, 使用switchTab
	if (tapBarList.includes(url)) {
		uni.navigateTo({
			url: `/${url}`
		})
		return true
	}
	// 生成query参数
	const querySrc = !isEmpty(query) ? `?${urlEncode(query)}` : ''
	// 普通页面跳转，使用navigateTo
	mode === 'navigateTo' && uni.navigateTo({
		url: `${url}${querySrc}`
	})
	// 特殊指定，使用redirectTo
	mode === 'redirectTo' && uni.redirectTo({
		url: `${url}${querySrc}`
	})

}

/**
 * 判断是否为空对象
 * @param {*} object 源对象
 */
export const isEmptyObject = (object) => {
	return Object.keys(object).length === 0
}

/**
 * 判断是否为数组
 *@param {*} array
 */
export const isArray = (array) => {
	return Object.prototype.toString.call(array) === '[Object Array]'
}

/**
 * 判断是否为对象
 *@param {*} Obejct
 */
export const isObject = (object) => {
	return Object.prototype.toString.call(object) === '[Object Obejct]'
}

/**
 * 判断是否为空
 * @param {*} object 源对象
 */
export const isEmpty = (value) => {
	if (isArray(value)) {
		return value.length === 0
	}
	if (isObject(value)) {
		return isEmptyObject(value)
	}
	return !value
}

/**
 * 对象转URL参数格式
 * {id:111,name:'xxx'} 转为 ?id=111&name=xxx
 * @param {object} obj
 */
export const urlEncode = (obj = {}) => {
	const result = []
	for (var key in obj) {
		let item = obj[key]
		if (!item) {
			continue
		}
		if (isArray(item)) {
			item.forEach(i => {
				result.push(`${key}=${i}`)
			})
		} else {
			result.push(`${key}=${item}`)
		}
	}
	return result.join('&')
}
/**
 * 是否在数组内
 */
export const inArray = (search, array) => {
	for (var i in array) {
		if (array[i] == search) return true
	}
	return false
}
/**
 * 判断对象里面的每个key值是否为空
 */
export const isEmptyObj = (object) => {
	let isEmpty = false
	Object.keys(object).forEach(el => {
		if (object[el] !== null && object[el] !== '') {
			isEmpty = true
		}
	})
	if (isEmpty) { return true } else { return false }
}

/**
 * 微信支付
 * 
 * callback 的回调  0=支付失败  1= 支付成功 2=取消支付
 */
export const wxPay = async (weChatApplet, callback,callPopup) => {
	// #ifdef H5
	// const dsbridge = require('./dsbridge.js')
	dsbridge.pay(weChatApplet, (value) => {
		if (value === 1) {
			// yuanbin 2021-09-01 15:29:44 暂时不使用store
			// store.commit("SET_PAPERSTYPE", 0)
			const orderId = weChatApplet.payAgain ? weChatApplet.orderId : weChatApplet.orderId.orderId
			request({
				url: `/funds/pay/payingOrder`,
				method: 'POST',
				params: {
					orderId: orderId
				}
			})
		}
		callback(value)
		payCallback(value, weChatApplet,callPopup)
	})
	// #endif

	// #ifndef H5
	await store.dispatch('GET_WECHAT', weChatApplet);
	let wxPayData = store.$state.payData
	// yuanbin 20250502 暂时不需要支付功能
	return
	uni.requestPayment({
		timeStamp: wxPayData.timeStamp, // 时间戳（单位：秒）
		nonceStr: wxPayData.nonceStr, // 随机字符串
		package: wxPayData.packagePrepayId, // 固定值
		signType: wxPayData.signType, //固定值
		paySign: wxPayData.paySign, //签名
		success: function (res) {
			console.log('success:' + JSON.stringify(res));
			console.log("支付成功");
			store.commit("SET_PAPERSTYPE", 0)

			callback(1)
			payCallback(1, weChatApplet,callPopup)
			let orderId = ""
			// #ifdef H5
			orderId = weChatApplet.payAgain ? weChatApplet.orderId : weChatApplet.orderId.orderId
			// #endif
			orderId = weChatApplet.orderId
			request({
				url: `/funds/pay/payingOrder`,
				method: 'POST',
				params: {
					orderId: orderId
				}
			})
		},
		fail: function (err) {
			console.log('fail:' + JSON.stringify(err));
			console.log("支付失败");
			postLog(err)
			callback(0)
			payCallback(0, weChatApplet,callPopup)
		}
	});
	// #endif
}
import appUtil from "./appUtil.js";
/**
 * 判断用户是否登录
 */
export const isLogin = (data, callback) => {
	let token = uni.getStorageSync("Authentication")
	if (!token) {
		appUtil.needLogin()
		return false
	} else {
		return true
	}
}
/**
 * 数组去重
 */
export const removeDuplicate = (arr) => {
	let len = arr.length
	for (let i = 0; i < len; i++) {
		for (let j = i + 1; j < len; j++) {
			if (arr[i].name === arr[j].name) {
				arr.splice(j, 1)
				len-- // 减少循环次数提高性能
				j-- // 保证j的值自加后不变
			}
		}
	}
	return arr
}
/**
 * 去除所有空格
 */
export const Trim = (str, is_global) => {
	var result;
	result = str.replace(/(^\s+)|(\s+$)/g, "");
	if (is_global.toLowerCase() == "g") {
		result = result.replace(/\s/g, "");
	}
	return result;
}
/**
 * 正则校验
 */
export const checkInput = (data, dataList) => {
	// checkData[i].validateType, checkData[i].inputValue, checkData[i].customerInfo
	let isPass = true
	let checkData = Trim(data.inputValue, "g")
	checkList.checkList.map(item => {
		if (data.validateType == item.id) {
			if (data.customerInfoId == 35) { //证件类型
				const findCurrent = dataList.find(e => e.customerInfoId == 41 && e.ranking === data.ranking)
				if (findCurrent && findCurrent.valueType == 2) { //身份证
					let data2 = checkData.toUpperCase() //转换成大写
					if (!IdentityCodeValid.validateIdent.IdentityCodeValid(data2)) {
						uni.showToast({
							title: `请检查${data.customerInfo}`,
							icon: "none"
						})
						isPass = IdentityCodeValid.validateIdent.IdentityCodeValid(data2)
					}

				}
			}
			// 中文姓名
			if (data.customerInfoId == 33) {
				const reg = /^[\u4e00-\u9fa5()\.·•]+$/
				if (!reg.test(checkData)) {
					uni.showToast({
						title: `请检查${data.customerInfo},请勿输入除“·•”外的特殊符号`,
						icon: "none"
					})
					isPass = false
				}
			}
			if (!item.reg.test(checkData)) {
				uni.showToast({
					title: `请检查${data.customerInfo}`,
					icon: "none"
				})
				isPass = false
			}
		}
	})
	return isPass
}
/**
 * 转换周
 */
export const getWeek = (timedata, type) => {
	var week;

	if (timedata.getDay() == 0) {
		week = '日';
	}

	if (timedata.getDay() == 1) {
		week = '一';
	}

	if (timedata.getDay() == 2) {
		week = '二';
	}

	if (timedata.getDay() == 3) {
		week = '三';
	}

	if (timedata.getDay() == 4) {
		week = '四';
	}

	if (timedata.getDay() == 5) {
		week = '五';
	}

	if (timedata.getDay() == 6) {
		week = '六';
	}
	const newWeek = type==="周" ? `周${week}` : `星期${week}`

	return newWeek;
}
/**
 * 日期转换为月日
 */
export const formatDatetoString = (value) => {
	const date = new Date(value);
	const month = date.getMonth() + 1;
	const day = date.getDate();
	return `${month}月${day}日`;
}
/**
 * 日期转换为月日对象格式
 */
export const formatDatetoObj = (value) => {
	const date = new Date(value);
	const month = (date.getMonth() + 1).toString().padStart(2, '0');
	const day = date.getDate().toString().padStart(2, '0');
	return {
		month,
		day
	};
}
/**
 * 预提交订单校验
 */
export const readySubmit = (data, callback) => {
	let checkData = data;
	let customerInfoCreateRequestList = []
	let allReady = true
	for (let i = 0; i < checkData.length; i++) {
		if (!checkInput(checkData[i], data)) {
			allReady = false
			//终止循环
			return false
		}
		let customerItem = {
			"customerInfoId": checkData[i].customerInfoId,
			"customerInfoValue": Trim(checkData[i].inputValue, 'g'),
			"ranking": checkData[i].ranking
		}
		customerInfoCreateRequestList.push(customerItem)
	}
	if (customerInfoCreateRequestList.length === 0) {
        uni.showToast({
          title: '网络异常，请重新进入页面~',
          icon: 'none',
          duration: 3000,
        })
        return;
    }
	if (allReady) {
		callback(customerInfoCreateRequestList)
	}
}
export const validateIdent = {
	aIdentityCode_City: { // 城市代码列表  
		11: "北京",
		12: "天津",
		13: "河北",
		14: "山西",
		15: "内蒙古",
		21: "辽宁",
		22: "吉林",
		23: "黑龙江 ",
		31: "上海",
		32: "江苏",
		33: "浙江",
		34: "安徽",
		35: "福建",
		36: "江西",
		37: "山东",
		41: "河南",
		42: "湖北 ",
		43: "湖南",
		44: "广东",
		45: "广西",
		46: "海南",
		50: "重庆",
		51: "四川",
		52: "贵州",
		53: "云南",
		54: "西藏 ",
		61: "陕西",
		62: "甘肃",
		63: "青海",
		64: "宁夏",
		65: "新疆",
		71: "台湾",
		81: "香港",
		82: "澳门",
		91: "国外 "
	},
	IdentityCode_isCardNo(card) { //检查号码是否符合规范，包括长度，类型  
		var reg = /(^\d{15}$)|(^\d{17}(\d|X)$)/; //身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X  
		if (reg.test(card) === false) {
			return false;
		}
		return true;
	},
	IdentityCode_checkProvince(card) { //取身份证前两位，校验省份    
		var province = card.substr(0, 2);
		if (validateIdent.aIdentityCode_City[province] == undefined) {
			return false;
		}
		return true;
	},
	IdentityCode_checkBirthday(card) { //检查生日是否正确，15位以'19'年份来进行补齐。  
		var len = card.length;
		//身份证15位时，次序为省（3位）市（3位）年（2位）月（2位）日（2位）校验位（3位），皆为数字    
		if (len == '15') {
			var re_fifteen = /^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/;
			var arr_data = card.match(re_fifteen); // 正则取号码内所含出年月日数据  
			var year = arr_data[2];
			var month = arr_data[3];
			var day = arr_data[4];
			var birthday = new Date('19' + year + '/' + month + '/' + day);
			return validateIdent.IdentityCode_verifyBirthday('19' + year, month, day, birthday);
		}
		//身份证18位时，次序为省（3位）市（3位）年（4位）月（2位）日（2位）校验位（4位），校验位末尾可能为X    
		if (len == '18') {
			var re_eighteen = /^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/;
			var arr_data = card.match(re_eighteen); // 正则取号码内所含出年月日数据  
			var year = arr_data[2];
			var month = arr_data[3];
			var day = arr_data[4];
			var birthday = new Date(year + '/' + month + '/' + day);
			return validateIdent.IdentityCode_verifyBirthday(year, month, day, birthday);
		}
		return false;
	},
	IdentityCode_verifyBirthday(year, month, day, birthday) { //校验日期 ，15位以'19'年份来进行补齐。
		var now = new Date();
		var now_year = now.getFullYear();
		//年月日是否合理    
		if (birthday.getFullYear() == year &&
			(birthday.getMonth() + 1) == month &&
			birthday.getDate() == day) {
			//判断年份的范围（3岁到150岁之间)    
			var time = now_year - year;
			if (time >= 3 && time <= 150) {
				return true;
			}
			return false;
		}
		return false;
	},
	IdentityCode_checkParity(card) { //校验位的检测  
		card = validateIdent.IdentityCode_changeFivteenToEighteen(card); // 15位转18位    
		var len = card.length;
		if (len == '18') {
			var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
			var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
			var cardTemp = 0,
				i, valnum;
			for (i = 0; i < 17; i++) {
				cardTemp += card.substr(i, 1) * arrInt[i];
			}
			valnum = arrCh[cardTemp % 11];
			if (valnum == card.substr(17, 1)) {
				return true;
			}
			return false;
		}
		return false;
	},
	IdentityCode_changeFivteenToEighteen(card) { //15位转18位身份证号   
		if (card.length == '15') {
			var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
			var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
			var cardTemp = 0,
				i;
			card = card.substr(0, 6) + '19' + card.substr(6, card.length - 6);
			for (i = 0; i < 17; i++) {
				cardTemp += card.substr(i, 1) * arrInt[i];
			}
			card += arrCh[cardTemp % 11];
			return card;
		}
		return card;
	},
	IdentityCodeValid(card) { //   身份证号码检验主入口 
		let pass = true;
		let sex = ''
		//是否为空    
		if (pass && card === '')
			pass = false;
		//校验长度，类型    
		if (pass && validateIdent.IdentityCode_isCardNo(card) === false)
			pass = false;
		//检查省份    
		if (pass && validateIdent.IdentityCode_checkProvince(card) === false)
			pass = false;
		//校验生日    
		if (pass && validateIdent.IdentityCode_checkBirthday(card) === false)
			pass = false;
		//检验位的检测    
		if (pass && validateIdent.IdentityCode_checkParity(card) === false)
			pass = false;
		if (pass) {
			var iCard = validateIdent.IdentityCode_changeFivteenToEighteen(card);
			if (parseInt(iCard.charAt(16)) % 2 == 0) {
				sex = "0"; // 女生  
			} else {
				sex = "1"; // 男生  
			}
			return true
		} else {
			return false
		}
	}
}
/**
 * 格式化模板（出行人等）
 */
export const formattingForm = (arr, title) => {
	let newArr = arr
	newArr.map(
		(item, index) => {
			item.valueType = "";
			item.inputValue = "";
			item.ranking = 1;
			item.typeName = title;
			if (item.customerInfoId == 41 || item.inputType == 54) {
				let splitData = item.templateOptionValue.split(",")
				item.inputValue = splitData[0];
				item.valueType = splitData[0];
				item.papersArr = splitData;
			}
			// 去掉日期选择器、时间选择器默认值
			// if (item.inputType == 56 || item.inputType == 58) {
			// 	let dateFormatter = formatDate(new Date(), "yyyy-MM-dd")
			// 	item.inputValue = dateFormatter;
			// 	item.valueType = dateFormatter;
			// }
			// if (item.inputType == 57) {
			// 	item.inputValue = "09:00";
			// 	item.valueType = "09:00";
			// }

			if (item.customerInfoId == 41) {
				//证件类型暂时单独判断
				let jsonData = JSON.parse(item.templateOptionValue)
				item.inputValue = jsonData[0].name;
				item.valueType = jsonData[0].validateTypeId;
				item.papersArr = JSON.parse(item.templateOptionValue);
				store.commit("SET_PAPERSTYPE", jsonData[0].validateTypeId);
			}
		}
	);
	return newArr
}
// 指定时间转换为时间戳
export const toTimeStamp = (dateString) => {
	// dateString例如:'2022-03-05'
	// 例如返回:1646611200000
	return new Date(dateString) - 0
}

// 计算两个日期距离的天数
export const getDistanceDays = (date1, date2) => {
	// date1例如:'2022-03-05',date2例如:'2022-03-06'
	const date1_timeStamp = toTimeStamp(date1)
	const date2_timeStamp = toTimeStamp(date2)
	let max = '', min = ''
	if (date1_timeStamp > date2_timeStamp) {
		max = date1_timeStamp
		min = date2_timeStamp
	} else {
		max = date2_timeStamp
		min = date1_timeStamp
	}
	// 例如返回:'1'
	return (max - min) / (24 * 60 * 60 * 1000)
}
//支付回调
/**
 * 
 * @param {*} code  0 失败 2 取消 1 成功
 * @param { Object } weChatApplet 
 */
export const payCallback = (code, weChatApplet,callBack) => { //code  支付状态 weChatApplet 支付参数
	console.log('codeck---',code)
	uni.removeStorageSync('poiConfig')
	let url = "/packageB/pages/myOrderList/myOrderList"
	let orderId = ""
	// #ifdef H5
	orderId = weChatApplet.payAgain ? weChatApplet.orderId : weChatApplet.orderId.orderId
	// #endif

	// #ifndef H5
	orderId = weChatApplet.orderId
	// #endif 
	if (code == 1) {
		if(weChatApplet.hopRoute == 3){//旅拍相册支付成功 不跳转订单页 并且不弹出订阅通知
			callBack()
			return
		}
		// #ifdef MP-WEIXIN
		wx.requestSubscribeMessage({
			tmplIds: ['r4nIbeyihvczt-G87sKXREg2rHLA0NhNPxduWxO7oys',
					'OM3I_zZg4tGlkLimcJHhJC9BU8stTkHrxVvbbQmtevs',
					'ucuqtHQLoDPvbRS65Two5Gg5-30g6QO5c7NXFJmzSnU'
					],
			success (res) { 
				console.log('订阅成功',res)
			}
		})
		// #endif
		
		if(weChatApplet.hopRoute == 2){//支付成功 不跳转订单页
			callBack()
			return
		}
		
		navTo(
			"/packageB/pages/paymentTips/paymentTips",
			{
				orderId: orderId,
				code
			},
			"redirectTo"
		);
	}
	if (code == 2 || code == 0 && weChatApplet.hopRoute == 1) {
		console.log(orderId)
		navTo(
			url,
			{
				status: 0,
				key: 1
			},
			"redirectTo"
		);

	}
}
//生成唯一id
export const setUuid = () => {
	var s = [];
	var hexDigits = "0123456789abcdef";
	for (var i = 0; i < 36; i++) {
		s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
	}
	s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
	s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
	s[8] = s[13] = s[18] = s[23] = "-";

	var uuid = s.join("");
	return uuid;
}
export const detailClick = (params) => {
	switch (params.contentType) {
		case "VIDEO":
			console.log(`跳视频播放`);
			noteVideoUrlJump("/packageB/pages/videoDetails/videoDetails", params.content)
			break;
		case "IMAGE":
			console.log(`跳笔记`);
			noteVideoUrlJump("/ai/pages/notedetails/notedetails", params.content)
			break;
		case "PRODUCT":
			console.log(`跳商品详情`);
			productUrlJump(params.content)
			break;
		case "ARTICLE":
			console.log(`跳游记详情`);
			noteVideoUrlJump("/packageApp/pages/travelNoteDetail/travelNoteDetail", params.content)
			break;
		default:
			productUrlJump(params.content)
			break;
	}
}
//列表跳转商品详情公共方法   data 商品详情实体，isFromList 是否从列表跳转
export const productUrlJump = (data, isFromList) => {
	let url = ``
	let {
		poiId,
		productId,
		supplierProductId,
		productType,
		toType,
		rpId,
		isCalendarHotel,
		distributionProductId
	} = data;
	let queryObj = {}
	if (toType == 1) {
		navTo(
			`/ai/pages/newProductDetail/productDetail?id=${productId}&distributionProductId=${distributionProductId}`,
			{},
			"navigateTo"
		);
	return;
	}

	if (productType == 'shareDSP') {//分享打包商品跳转
		navTo(
			`/ai/pages/productDetail/productDetail`,
			{...data},
			"navigateTo"
		);
	return;
	}
	if(isCalendarHotel) {
		navTo(
			`/packageAI/pages/aiHotelInfo/aiHotelInfo?productId=${supplierProductId}&rpId=${rpId}&stdId=${productId}&distributionProductId=${distributionProductId}`,
			{},
			"navigateTo"
		);
		return
	}

	switch (productType) {
		case "01"://门票
			queryObj = {
				poiId: poiId,
				distributionProductId: distributionProductId? distributionProductId : '',
				supplierProductId,
			}
			url = '/ai/pages/POIDetail/index'
			break;
		case "07"://日游
		case "10"://茶馆
		case "11"://旅拍
		case "13"://权益券
		case "02"://餐厅
			queryObj = {
				poiId: poiId,
				productType,
				stdId: productId,
				supplierProductId,
				distributionProductId: distributionProductId? distributionProductId : '',
				isFromList,
			}
			url = `/ai/pages/productDetail/productDetail`;
			break;
		case "04"://酒店   由于服务端字段定义多个导致 supplierProductId = productId  stdId = productId
			queryObj = {
				checkinTime: data.checkinTime,
				checkoutTime:data.checkoutTime,
				productId: data.supplierProductId,
				rpId: data.rpId,
				stdId: data.productId,
				storeId: data.storeId
			}
			url = `/packageAI/pages/aiHotelInfo/aiHotelInfo`;
			break;
		default:
			queryObj = {
				poiId: poiId,
				productType,
				stdId: productId,
				supplierProductId,
				distributionProductId: distributionProductId? distributionProductId : ''
			}
			url = `/ai/pages/POIDetail/index`;
			break;
	}
	console.log('queryObj', queryObj);
	navTo(
		url,
		queryObj,
		"navigateTo"
	);
}
export const noteVideoUrlJump = (url, e) => {
	const { articleId } = e;
	navTo(
		url,
		{
			articleId,
		},
		"navigateTo"
	);
}

/* 缓存的spm埋点数据，以event_type为Key，每种类型的只会缓存一个*/
const _cacheSPMData = {}
const addSPMCache = (params) => {
	const event = params.events[0]
	const event_id = event.event_id
	///暂时只对页面离开做去重
	if (event_id != '2003') return
	_cacheSPMData[event.event_id] = { ...event }
}
/* 去重 */
const deweightSPMData = (params) => {
	const event = params.events[0]
	const event_id = event.event_id
	///暂时只对页面离开做去重
	if (event_id != '2003') {
		return true
	}
	const lastData = _cacheSPMData[event.event_id]
	///不存在上一次同一类型的上报
	if (!lastData) {
		addSPMCache(params)
		return true
	}
	///判断是否超过阈值
	if (event_id !== '2003' && event.spm_cnt !== lastData.spm_cnt && event.open_time !== lastData.open_time) {
		addSPMCache(params)
		return true
	}
	return false
}

var _cacheLastEventid = ''
/**
 * 最后缓存的事件是否位离开事件
 * @param {*} params 
 * @returns 
 */
const lastSpmDataIsClose = (params) => {
	const event = params.events[0]
	const event_id = event.event_id

	if (_cacheLastEventid && _cacheLastEventid == event_id && event_id == '2003') {
		return true
	}

	_cacheLastEventid = event_id

	return false
}

export const spmFun = (pointData, data) => {
	let params = pointData
	const nowTime = new Date().getTime()
	//	#ifdef H5
	// const dsbridges = require('./dsbridge.js')
	let getAppSpmParam = JSON.parse(dsbridges.getAppSpmParam())
	params.common = getAppSpmParam.common ?? {}
	params.events[0].spm_ref = data.spm_ref ? data.spm_ref : getAppSpmParam.events[0].spm_cnt//上级页面点击位置
	params.events[0].spm_pre = data.spm_pre ? data.spm_pre : getAppSpmParam.events[0].spm_pre //上上级点击位置
	if (data.event_id === "2003") {
		dsbridges.sendSpmParamToNative({ ref: data.spm_cnt, pre: data.spm_ref });
	}
	//	#endif

	// #ifdef MP-WEIXIN
	let userInfo = uni.getStorageSync("currUser")
	if(!userInfo){
		userInfo = { // 测试用， 防止报错
			userId: '',
			nickname: ''
		}
	}
	if(!params.common){
		params.common = { // 测试用， 防止报错
			userId: '',
			nickname: ''
		}
	}
	params.common.user_id = userInfo.userId
	params.common.user_nick = userInfo.nickname
	params.common.client_time = nowTime
	params.events[0].spm_ref = data.spm_ref ? data.spm_ref : ''//上级页面点击位置
	params.events[0].spm_pre = data.spm_pre ? data.spm_pre : '' //上上级点击位置
	let equipmentId = uni.getStorageSync("Uuid")
    if(equipmentId){
      params.common.equipment_id = equipmentId
    }
	if(uni.getStorageSync('scene')){
		params.common.scene = uni.getStorageSync('scene')
	}
	//	#endif

	params.events[0].client_event_time = nowTime
	params.events[0].event_id = data.event_id
	params.events[0].event_type = data.event_type
	params.events[0].spm_cnt = data.spm_cnt

	params.events[0].open_time = data.open_time ? data.open_time : ""
	params.events[0].leave_time = nowTime
	if (data.video_load_start_time) {
		params.events[0].video_load_start_time = data.video_load_start_time
		params.events[0].video_load_end_time = data.video_load_end_time
		params.events[0].video_start_time = data.video_start_time
		params.events[0].video_end_time = data.video_end_time
		params.events[0].sum_play_time = data.sum_play_time
		params.events[0].max_play_time = data.max_play_time
	}

	if (data.event_id === "2001") {
		// 曝光事件
		params.events[0].exposure_start_time = data.exposure_start_time
		params.events[0].exposure_end_time = data.exposure_end_time
	}

	params.events[0].args = data.args
	///去重
	if (lastSpmDataIsClose(params)) return
	if (data.event_id === "2004" || data.event_id === "19999") {
		store.commit('spm/SET_PARENT_SPM', { ref: data.spm_cnt, pre: data.spm_ref })
	}
	// #ifdef MP-WEIXIN
	if (data.event_id === "2003" && (data.spm_cnt.indexOf(".HomePage.") != -1 || data.spm_cnt.indexOf(".Mine.") != -1)) {
		store.commit('spm/SET_PARENT_SPM', { ref: data.spm_cnt, pre: data.spm_ref }) // 如果是离开页面就把当前页面信息替换来源页
	}
	// #endif
	request({
		url: '/spm',
		method: 'POST',
		params
	})
}
export const returnState = () => {
	console.log(" store.$state.pointData", store.$state.pointData)
	let returnData = {
		pointData: store.$state.pointData,
		spmData: store.$state.spmData
	}
	return returnData
}
export const getUserInfo = (pRes, options, delta) => {
	let that = this
	uni.setStorageSync('Authentication', pRes.data.token);
	// store.commit('SET_TOKEN', pRes.data.token);
	store.SET_TOKEN(pRes.data.token)
	try {
		request({
			url: '/wechat/getCurrUser',
			method: 'POST',
			header: {
				'Content-Type': 'application/json'
			}
		}).then(res => {
			if (res.success) {
				uni.setStorageSync('openid', res.data.openid);
				uni.setStorageSync('currUser', res.data);
				store.SET_lOGIN(false);
				// uni.$emit(Events.loginOverEvent);
				// if (options.synchronous) {
				// 	navTo(
				// 		'/packageB/pages/myOrderList/myOrderList', { status: 3, key: 3 }, "redirectTo"
				// 	)
				// } else {
				// 	// uni.switchTab({
				// 	// 	url: '/pages/newHome/newHome'
				// 	// })
				// 	uni.navigateBack({
				// 		delta: delta ? delta : 1
				// 	})
				// }
			} else {
				uni.removeStorageSync('Authentication');
                store.SET_TOKEN('')//登录失效清除store
				uni.showToast({
					title: `${res.errMsg}`,
					icon: 'none',
					mask: true
				})
			}
		});
	} catch (error) {
		uni.removeStorageSync('Authentication')
		store.SET_TOKEN('')//登录失效清除store
	}
}

export const shareStatistical = (res) => {
	let params = {
		"distributorId": res.distributorId,
		"distributorNick": res.distributorNick,
		"distributorType": res.distributorType,
		"productId": res.supplierProductId,
		"userId": uni.getStorageSync("currUser").userId
	}
	request({
		url: '/commission/scanRecord',
		method: 'POST',
		params
	})
}
export const openLocation = (data) => {
	// #ifdef H5
	// const dsbridge = require("./dsbridge");
	dsbridge.openLocation(data);
	// #endif

	// #ifndef H5
	uni.openLocation(data);
	// #endif
}
//dsp poi详情
export const poiClick = (data) => {
	if (!data.isDisplayDetails) return
	navTo(
		'/ai/pages/POIDetail/index',
		{
			poiId: data.poiId
		},
		"navigateTo"
	)
}
//获取预订须知
export const reservationNotice = (params) => {
	return request({
		url: `/product/reservationNotice`,
		method: 'POST',
		params
	})
}

let audioResultsList = []

// 音频播放方法
export const playAudio = async (id,results,playbackRate)=> {
	return new Promise((resolve, reject) => {
		payload(id,results, playbackRate)
		innerAudioContext.onEnded((res) => {
			id++
			if(id < results.length){
				console.log('播放了======', id, playbackRate)
				payload(id,results, playbackRate)
			}
			// if(fn){fn(innerAudioContext)}
			// 播放完成回调，需要处理播放停止按钮和状态
			if(results.length === id) {
				resolve(innerAudioContext)
			}
		})
		
	})
}

// 创建音频, 返回音频上下文和音频文件
export const createPlayAudio = async(id,txt,voiceType, playbackRate)=> {
	
	audioResultsList = []
	let txtArr = []
	var that = this;
	let extras = txt
	var lastExtras;
	var extrasArr = []
	// 提取汉字(由于笔者要播报的来自富文本，所以需要提取文字)

	return new Promise(async (resolve, reject) => {
		if (extras != null && extras != '') {
			// 去掉html标签
			lastExtras = extras.replace(/<[^>]+>/g, "");
			// 只留汉字和数字
			lastExtras = lastExtras.replace(/\n/g, "")
			extrasArr = lastExtras.split(/[：，]+/)
		}
		for (let i = 0; i < extrasArr.length; i++) {
			if (extrasArr[i]) {
				txtArr.push(extrasArr[i])
			}
		}
	    let audioResultsList = await fetchData(extrasArr, voiceType, playbackRate)
		resolve([audioResultsList, innerAudioContext])
	})
}

export const  fetchData = async (extrasArr, voiceType,playbackRate) =>{
	console.log('音色', voiceType, playbackRate)
	return new Promise((resolve,reject) => {
		const promises = extrasArr.map((text) => {
			return new Promise((resolve, reject) => {
			  plugin.textToSpeech({
				  content: text,
				  speed: Number(playbackRate),
				  volume: 0,
				  voiceType: Number(voiceType), // 音色
				  language: 1,
				  projectId: 0,
				  sampleRate: 16000,
				  success: function (data) {
					//   let url = data.result.filePath;
					  let url
					  if (data.result.filePath.includes('?')) {
						  url = data.result.filePath.split('?')[0];
					  } else {
						  url = data.result.filePath
					  }
					  resolve(url)
				  },
				  error: function (err) {
					  console.log(err);
				  },
				  fail: function (error) {
					  console.log(error);
				  }
			  })
			})
		  })
		  Promise.all(promises).then((results) => {
			 results
				if (results && results.length > 0) {
				  audioResultsList = results
				  resolve(audioResultsList)
			  }
		  }).catch((err) => {
			console.log('请求失败：', err)
		  })
	})
  }

export const initSpeechRecognizerManager = () => {
	let speechRecognizerManager = plugin.speechRecognizerManager();
	const params = {

		// 用户参数
		secretkey: '84pOKAp9VltY5SgnlYCfz85tX1KUSIyT',
		secretid:  'AKIDHQNDtOiqlT0NXT0RiowwlcKrEQQQFsJZ',
		appid: 1358329933,  // 腾讯云账号appid（非微信appid）
		token: '',  // 选填参数，若密钥为临时密钥，需传此参数。

		// 实时识别接口参数
		engine_model_type : '16k_zh',
		// voice_format: 1, // 1 为 pcm, 8为 mp3, 目前仅支持mp3和pcm
		// 以下为非必填参数，可跟据业务自行修改
		// hotword_id : '08003a00000000000000000000000000',
		// needvad: 0,
		// filter_dirty: 1,
		// filter_modal: 2,
		// filter_punc: 0,
		// convert_num_mode : 1,
		// word_info: 2,
		// vad_silence_time: 200
	}
	speechRecognizerManager.start(params)
	return speechRecognizerManager
}
//  播放音频
export const payload = (index, results, playbackRate) => {
	innerAudioContext.autoplay = true;
	innerAudioContext.loop = false;
	innerAudioContext.playbackRate = '1.0' // 语速
	innerAudioContext.src = results[index];
	innerAudioContext.onPlay(() => {
	});
	innerAudioContext.onError((res) => {
		console.log(res.errMsg)
	});
  }
  //分享函数
export const shareFun = (obj,title,url,imageUrl) => {
	var encoded = [];
	for (var key in obj) {
		encoded.push(encodeURIComponent(key) + "=" + encodeURIComponent(obj[key]));
	}
	let shareUrl =	url ? url + "?" + encoded.join("&") : '/ai/pages/index' + "?" + encoded.join("&");
	return {
		title:title?title:'',
    	path: shareUrl,
		imageUrl: imageUrl ? imageUrl : '',
	}
}


export const getChatAiImg = () => {
	request({
		url: '/ai/aihub/chat/floatingWindow/icon',
		method: 'GET',
	}).then(res => {
		if (res.success) {
			uni.setStorageSync("chatAIImg", res.data)
		}
	});
}

/**
 * 睡眠函数
 * @param { Number } ms 睡眠时间 毫秒
 * @returns 
 */
export const sleep = (ms) => {
	return new Promise((resolve) => setTimeout(resolve, ms));
}

export default {
	isLogin,
	wxPay,
	removeDuplicate,
	checkInput,
	getWeek,
	Trim,
	readySubmit,
	validateIdent,
	formattingForm,
	getDistanceDays,
	payCallback,
	setUuid,
	detailClick,
	spmFun,
	returnState,
	getUserInfo,
	shareStatistical,
	isEmptyObj,
	openLocation,
	navBack,
	poiClick,
	reservationNotice,
	playAudio,
	createPlayAudio,
	formatDatetoString,
	formatDatetoObj,
	shareFun,
	getChatAiImg,
	sleep
}
